package com.sneakxy.mybatis.commons.dialect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.Configuration;

public class DialectFactory {

	private static final Map<String, Class<? extends Dialect>> DIALECTS = new LinkedHashMap<>(2);
	
	static {
		DIALECTS.put(MySqlDialect.DIALECT_NAME, MySqlDialect.class);
		DIALECTS.put(OracleDialect.DIALECT_NAME, OracleDialect.class);
	}
	
	public static Dialect getDialect(Configuration configuration, String name) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		if(StringUtils.isBlank(name)) {
			return new MySqlDialect(configuration);
		}
		if(DIALECTS.containsKey(name)) {
			Class<? extends Dialect> clazz = DIALECTS.get(name);
			return clazz.getConstructor(Configuration.class).newInstance(configuration);
		}
		try {
			Class<?> clazz = Class.forName(name);
			Constructor<?> constructor = clazz.getConstructor(Configuration.class);
			return (Dialect) constructor.newInstance(configuration);
		} catch (ClassNotFoundException e) {}
		return null;
	}
	
}
